from rest_framework.permissions import IsAdminUser
from rest_framework.views import APIView, Response
import datetime
from users.models import User
from goods.models import GoodsVisitCount
from meiduo_admin.serializers import statistical

class UserCountView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        now_time = datetime.date.today()
        count = User.objects.all().count()
        return Response({
            'count': count,
            'date': now_time
        })


class UserAddView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        now_time = datetime.date.today()
        count = User.objects.filter(date_joined__gte=now_time).count()
        return Response({
            "count": count,
            "date": now_time
        })


class UserActiveView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        now_time = datetime.date.today()
        count = User.objects.filter(last_login__gte=now_time).count()
        return Response({
            "count": count,
            "date": now_time
        })


class UserOrdersView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        now_time = datetime.date.today()
        # 查找当日下单的用户
        # a = User.orders
        count = len(set(User.objects.filter(orders__create_time__gte=now_time)))

        return Response({
            "count": count,
            "date": now_time
        })


class UserMonthCountView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        now_time = datetime.date.today()
        begin_date = now_time - datetime.timedelta(days=30)
        counts = []
        for i in range(31):
            count = User.objects.filter(date_joined__gte=begin_date,date_joined__lt=(begin_date+datetime.timedelta(days=1))).count()

            counts.append({
                "count": count,
                "date": begin_date
            })
            begin_date = begin_date + datetime.timedelta(days=1)

        return Response(counts)

class GoodsDayView(APIView):
    permission_classes = [IsAdminUser]
    def get(self,request):
        now_time = datetime.date.today()
        goods = GoodsVisitCount.objects.filter(date__gte=now_time)
        ser = statistical.UserGoodsCountSerializer(instance=goods,many=True)
        return Response(ser.data)
